'''
006 Veggie Ninja
Controls:       Touch and Drag
Description:    Cut those filthy vegetables!
'''
TRAIL_LENGTH = 3;
GRAVITY = 1;
TOTAL_VEGETABLES = 7;

import pygame
import spyral
import random
import math


class game006(spyral.scene.Scene):
    def __init__(self, player):
        spyral.scene.Scene.__init__(self)
        self.root_camera = spyral.director.get_camera()
        self.camera = self.root_camera.make_child(layers = [0,1,2,3])
        self.group = spyral.sprite.Group(self.camera)
        
        self.player = player;
        self.timer = Timer.Timer(self.player.current_speed);
        
        self.mouseTrail = [];
        self.mouse_prev_pos = (0, 0);
        self.mouse_cur_pos = (0, 0);
        self.clicked = False;
        self.counter = 0;
        self.vegetable_cut = 0;
        self.vegetable_made = 0;
        self.vegetable_max = 3;
        
        self.veg = [];

        self.group.add(self.timer);
        
        
    def on_enter(self):
        bg = spyral.util.load_image(Dic.images['006bg'])
        self.camera.set_background(bg)
        
    def render(self):
        self.group.draw()
        self.root_camera.draw()
        
    def update(self, tick):
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    spyral.director.pop()
                    exit(0)
                if event.key == pygame.K_r:
                    spyral.director.replace(game006(self.player))
            if (self.clicked == False):
                if event.type == pygame.MOUSEBUTTONDOWN:
                    self.cur_mouse_pos = pygame.mouse.get_pos()
                    self.clicked = True;
            elif (self.clicked == True):
                if event.type == pygame.MOUSEBUTTONUP:
                    self.clicked = False;
                    self.deleteTrail();
        
        #create mouse trail
        if (self.clicked == True):
            self.prev_mouse_pos = self.cur_mouse_pos;
            self.cur_mouse_pos = pygame.mouse.get_pos();
            if (len(self.mouseTrail) == TRAIL_LENGTH):
                #delete tail
                self.mouseTrail.pop(0).kill();
            trail = slice(self.prev_mouse_pos, self.cur_mouse_pos);
            self.mouseTrail.append(trail);
            self.group.add(trail);
       
        #create vegetables
        self.counter += 1;
        if (self.counter == 16):
            if (self.vegetable_made < self.vegetable_max):
                self.makeVegetable();
                self.vegetable_made += 1;
                self.counter = 0;
        
        #check if any vegetable are cut
        if (len(self.mouseTrail) != 0):
            #sliced
            if (len(self.veg) != 0):
                self.checkSlice();
        
        #check timer
        if (self.timer.timesUp()):
            if (self.winCondition() == False):
                self.player.decHealth();
            else:
                self.player.incCurrentGamesCompleted();
            spyral.director.pop()
        
        self.group.update();
 
    def winCondition(self):
        if (self.vegetable_cut == self.vegetable_max):
            return True;
        else:
            return False;
    
    def deleteTrail(self):
        while (len(self.mouseTrail) != 0):
            self.mouseTrail.pop(0).kill();
    
    def checkSlice(self):
        trail = self.mouseTrail[len(self.mouseTrail) - 1]
        for veg in self.veg:
            if (pygame.sprite.collide_mask(trail, veg)):
                if (20 <= trail.getLength()):
                    self.vegetable_cut += 1;
                    trail = self.mouseTrail[len(self.mouseTrail) - 1]
                    veg.setAngle(trail.getAngle())
                    slices = veg.slice();
                    self.group.add(slices[0], slices[1])
                    veg.kill();
                    self.veg.remove(veg);
                    
    
    def makeVegetable(self):
        veg = vegetable()
        self.veg.append(veg)
        self.group.add(veg)




class slice(spyral.sprite.Sprite):
    def __init__(self, pt1, pt2):
        spyral.sprite.Sprite.__init__(self);
        self.pt1 = pt1;
        self.pt2 = pt2;
        if (self.pt1 == self.pt2):
            self.length = 2;
        else:
            self.length = self.getLength();
        self.image = spyral.util.new_surface(self.length, 2)
        self.image.fill(Dic.colors['white'])
        if (self.pt1 != self.pt2):
            self.rotateImage()
        self.rect.center = self.getMidpoint();
        self.layer = 2;
        
        self.mask = pygame.mask.from_surface(self.image);
    
    def getLength(self):
        length =  math.sqrt(math.pow(self.pt2[0] - self.pt1[0], 2) + math.pow(self.pt2[1] - self.pt1[1], 2));
        return length
    
    def getMidpoint(self):
        x = (self.pt1[0] + self.pt2[0]) / 2;
        y = (self.pt1[1] + self.pt2[1]) / 2;
        return (x, y);
    
    def getAngle(self):
        angle = math.degrees(math.asin(float(self.pt1[1] - self.pt2[1]) / self.length));
        if (self.pt2[0] < self.pt1[0]):
            return -angle;
        else:
            return angle;
    
    def rotateImage(self):
        self.image = pygame.transform.rotate(self.image, self.getAngle())
        
class vegetable(spyral.sprite.Sprite):
    def __init__(self):
        spyral.sprite.Sprite.__init__(self);
        self.randomVegetable();
        if (self.type == 'carrot'):
            self.img_original = spyral.util.load_image(Dic.images['006veg1a'])
            self.slice_images = [Dic.images['006veg1b'], Dic.images['006veg1c']]
            self.slice_position = [(-31, 78), (10, -31)]
        elif (self.type == 'tomato'):
            self.img_original = spyral.util.load_image(Dic.images['006veg2a'])
            self.slice_images = [Dic.images['006veg2b'], Dic.images['006veg2c']]
            self.slice_position = [(0, -31), (0, 33)]
        elif (self.type == 'broccoli'):
            self.img_original = spyral.util.load_image(Dic.images['006veg3a'])
            self.slice_images = [Dic.images['006veg3b'], Dic.images['006veg3c']]
            self.slice_position = [(3, -45), (-5, 45)]
        elif (self.type == 'pepper'):
            self.img_original = spyral.util.load_image(Dic.images['006veg4a'])
            self.slice_images = [Dic.images['006veg4b'], Dic.images['006veg4c']]
            self.slice_position = [(0, -33), (-2, 37)]
        elif (self.type == 'onion'):
            self.img_original = spyral.util.load_image(Dic.images['006veg5a'])
            self.slice_images = [Dic.images['006veg5b'], Dic.images['006veg5c']]
            self.slice_position = [(4, -24), (1, 40)]
        elif (self.type == 'garlic'):
            self.img_original = spyral.util.load_image(Dic.images['006veg6a'])
            self.slice_images = [Dic.images['006veg6b'], Dic.images['006veg6c']]
            self.slice_position = [(10, -5), (10, 40)]
        elif (self.type == 'chili'):
            self.img_original = spyral.util.load_image(Dic.images['006veg7a'])
            self.slice_images = [Dic.images['006veg7b'], Dic.images['006veg7c']]
            self.slice_position = [(-25, -43), (11, 40)]

        self.image = self.img_original;
        self.layer = 1;

        self.angle = 0;
        
        self.mask = pygame.mask.from_surface(self.image);
    
    def update(self, tick):
        self.yvel -= GRAVITY;
        self.rect.center = (self.rect.center[0] + self.xvel,
                            self.rect.center[1] - self.yvel);
        self.angle += self.rotate_speed;
        self.rotateImage()
                
                
    def rotateImage(self):
        oldcenter = self.rect.center;
        self.image = pygame.transform.rotate(self.img_original, self.angle)
        self.rect = self.image.get_rect();
        self.rect.center = oldcenter;
        self.mask = pygame.mask.from_surface(self.image);
    
    def slice(self):
        new_positions = self.calcNewSlicePositions();
        new_xvels = self.calcNewXVels(new_positions);
        slice1 = slicedVegetable(self.slice_images[0], self.angle, new_positions[0], new_xvels[0], self.yvel)
        slice2 = slicedVegetable(self.slice_images[1], self.angle, new_positions[1], new_xvels[1], self.yvel)
        return [slice1, slice2]
        self.kill();
    
    def calcNewSlicePositions(self):
        angle = math.radians(self.angle)
        origin = self.rect.center;
        pos1 = self.slice_position[0];  
        pos1 = (origin[0] + pos1[0], origin[1] + pos1[1]);
        pos1x = origin[0] + math.cos(angle) * (pos1[0] - origin[0]) - math.sin(angle) * -1*(pos1[1] - origin[1]);
        pos1y = origin[1] - math.sin(angle) * (pos1[0] - origin[0]) + math.cos(angle) * (pos1[1] - origin[1]);
        pos1 = (pos1x, pos1y)
        pos2 = self.slice_position[1];
        pos2 = (origin[0] + pos2[0], origin[1] + pos2[1]);
        pos2x = origin[0] + math.cos(angle) * (pos2[0] - origin[0]) - math.sin(angle) * -1*(pos2[1] - origin[1]);
        pos2y = origin[1] - math.sin(angle) * (pos2[0] - origin[0]) + math.cos(angle) * (pos2[1] - origin[1]);
        pos2 = (pos2x, pos2y)
        return [pos1, pos2]
    
    def setAngle(self, angle):
        self.angle = angle;
        
    def calcNewXVels(self, new_positions):
        if (new_positions[0][0] <= new_positions[1][0]):
            return [-self.xvel + 5, self.xvel - 5]
        else:
            return [self.xvel - 5, -self.xvel + 5]
    
    def randomVegetable(self):
        types = ['carrot', 'tomato', 'broccoli', 'pepper', 'onion', 'garlic', 'chili'];
        self.type = types[random.randint(0, TOTAL_VEGETABLES - 1)];
        pos_and_vels = [[(100, 800), 15, 35], [(700, 800), -13, 30], [(-200, 300), 20, 15], [(1050, 400), -23, 20]]
        pos_and_vels = pos_and_vels[random.randint(0,3)]
        self.rect.center = pos_and_vels[0];
        self.xvel = pos_and_vels[1];
        self.yvel = pos_and_vels[2];
        self.angle = random.randint(0,359)
        self.rotate_speed = random.randint(-6, 6)
        
        
    

class slicedVegetable(spyral.sprite.Sprite):
    def __init__(self, image, angle, center, xvel, yvel):
        spyral.sprite.Sprite.__init__(self);
        self.img_original = spyral.util.load_image(image);
        self.image = self.img_original;
        self.rect.center = center;
        self.layer = 1;
        self.angle = angle;
        self.rotateImage();
        self.xvel = xvel;
        self.yvel = yvel;
    
    def update(self, tick):
        self.yvel -= GRAVITY;
        self.rect.center = (self.rect.center[0] + self.xvel,
                            self.rect.center[1] - self.yvel);
        self.angle += 1;
        self.rotateImage()
        
        if (Dic.geom['height'] < self.rect.top):
            self.kill();
        
    
    def rotateImage(self):
        oldcenter = self.rect.center;
        self.image = pygame.transform.rotate(self.img_original, self.angle)
        self.rect = self.image.get_rect();
        self.rect.center = oldcenter;

    




if __name__ == "__main__":
    import sys
    sys.path.append("C:\Users\Patrick\paybackpigs\paybackpigs")
    from frenzy import Dic
    Dic.setImgFolder('../images/')
    from frenzy import Image
    from frenzy import Timer
    from frenzy import Player
    spyral.init()
    spyral.director.init(Dic.geom['size'], False, 'Payback Pigs', 30, 30)
    spyral.director.push(game006(Player.Player()))
    spyral.director.run()

else:
    import Image
    import Dic
    import Timer;